package com.baizhi.Controller;

import com.baizhi.util.ESUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PoenController {
    @GetMapping("poems")
    public Map<String,Object> selectList(int page,int limit){
        List list=new ArrayList();
        TransportClient client = ESUtils.getClient();
        //设置查询方案:.setQuery()
        //查询所有：QueryBuilders.matchAllQuery()
        //条件查询:QueryBuilders.termQuery(name:"name",value:"三")
        SearchResponse searchResponse = client.prepareSearch("es3").setTypes("poetries").setQuery(QueryBuilders.matchAllQuery()).setFrom(page)
                .setSize(limit).get();
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            //将json字符串转化成map集合
            Map<String,Object> map= hit.getSourceAsMap();
            list.add(map);
        }
        return new HashMap(){{
            put("msg","");
            put("code",0);
            put("data",list);
            put("count",hits.getTotalHits());
        }};
    }
}
